package com.share.example.stock.schedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.utils.DateUtil;
import com.share.example.stock.model.db.ScheduleLog;
import com.share.example.stock.model.db.TradeDate;
import com.share.example.stock.service.IScheduleLogService;
import com.share.example.stock.service.ITradeDateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class S00_Down_trade {
    private String className = this.getClass().getSimpleName();
    @Autowired
    private IScheduleLogService iScheduleLogService;

    @Autowired
    private ITradeDateService iTradeDateService;

    @PostConstruct
    @Scheduled(cron = "10 10/30 * * * ?")
    public void initTradeDate() {
        iTradeDateService.initTradeDate();
    }

    @Scheduled(cron = "0 * 4 * * ?")//每天执行一次
    public void downDate() {
        LambdaQueryWrapper<TradeDate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(TradeDate::getDate, DateUtil.getDate(5));//大于等于
        long count = iTradeDateService.count(queryWrapper);
        if (count > 10) {
            log.info("日志数据存在条数={},将跳过", count);
            return;
        }

        String jobCode = className + "_" + "downDate";

        //开始日志
        ScheduleLog insertLog = iScheduleLogService.insertLog(jobCode);

        //开始下载数据库
        ScheduleLog upLog = new ScheduleLog().setId(insertLog.getId());
        try {
            List<String> list = iTradeDateService.downDate();
            upLog.setStatus("1");
            upLog.setRemark("数据条数=" + (list == null ? 0 : list.size()));
        } catch (Exception e) {
            upLog.setExpMsg(e.getMessage());
            log.error("下载失败", e);
        }

        //更新日志
        iScheduleLogService.updateLogById(upLog);
    }
}
